package com.xuetang.service.impl;

import com.xuetang.entity.BloodSugarRecord;
import com.xuetang.mapper.BloodSugarRecordMapper;
import com.xuetang.service.BloodSugarRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 血糖记录服务实现类
 */
@Service
public class BloodSugarRecordServiceImpl implements BloodSugarRecordService {

    @Autowired
    private BloodSugarRecordMapper bloodSugarRecordMapper;

    @Override
    public List<BloodSugarRecord> getByUserIdAndDate(Long userId, LocalDate date) {
        return bloodSugarRecordMapper.selectByUserIdAndDate(userId, date);
    }

    @Override
    public List<BloodSugarRecord> getByUserIdAndDateRange(Long userId, LocalDate startDate, LocalDate endDate) {
        return bloodSugarRecordMapper.selectByUserIdAndDateRange(userId, startDate, endDate);
    }

    @Override
    public List<BloodSugarRecord> page(Long userId, Integer type, int page, int size) {
        int offset = (page - 1) * size;
        return bloodSugarRecordMapper.selectPageByUserId(userId, type, offset, size);
    }

    @Override
    public int count(Long userId, Integer type) {
        return bloodSugarRecordMapper.countByUserId(userId, type);
    }

    @Override
    @Transactional
    public BloodSugarRecord saveRecord(BloodSugarRecord record) {
        // 注意：数据库表中没有status字段，所以不设置状态
        // record.setStatus(determineStatus(record.getValue().doubleValue(),
        // record.getMeasureType()));

        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        record.setCreateTime(now);
        record.setUpdateTime(now);

        // 保存记录
        bloodSugarRecordMapper.insert(record);
        return record;
    }

    @Override
    @Transactional
    public BloodSugarRecord updateRecord(BloodSugarRecord record) {
        // 注意：数据库表中没有status字段，所以不设置状态
        // if (record.getValue() != null && record.getMeasureType() != null) {
        // record.setStatus(determineStatus(record.getValue().doubleValue(),
        // record.getMeasureType()));
        // }

        // 设置更新时间
        record.setUpdateTime(LocalDateTime.now());

        // 更新记录
        bloodSugarRecordMapper.updateById(record);
        return record;
    }

    @Override
    @Transactional
    public boolean deleteById(Long id, Long userId) {
        return bloodSugarRecordMapper.deleteById(id, userId) > 0;
    }

    @Override
    public BloodSugarRecord getById(Long id) {
        return bloodSugarRecordMapper.selectById(id);
    }

    @Override
    public Map<String, Object> getStatistics(Long userId, String timeRange) {
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = getStartDateByTimeRange(endDate, timeRange);

        // 查询统计数据
        Map<String, Object> statistics = bloodSugarRecordMapper.selectStatistics(userId, startDate, endDate);

        // 如果没有数据，返回默认值
        if (statistics == null) {
            statistics = new HashMap<>();
            statistics.put("average", BigDecimal.ZERO);
            statistics.put("highest", BigDecimal.ZERO);
            statistics.put("lowest", BigDecimal.ZERO);
            statistics.put("total", 0);
        }

        // 查询所有记录，计算正常和异常记录数
        List<BloodSugarRecord> records = bloodSugarRecordMapper.selectByUserIdAndDateRange(userId, startDate, endDate);
        int normalCount = 0;
        int abnormalCount = 0;

        for (BloodSugarRecord record : records) {
            // 使用determineStatus方法判断每条记录的状态
            int status = determineStatus(record.getValue().doubleValue(), record.getMeasureType());
            if (status == 1) { // 正常
                normalCount++;
            } else { // 异常（偏高或偏低）
                abnormalCount++;
            }
        }

        statistics.put("normalCount", normalCount);
        statistics.put("abnormalCount", abnormalCount);

        return statistics;
    }

    @Override
    public List<Map<String, Object>> getTrend(Long userId, String timeRange) {
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = getStartDateByTimeRange(endDate, timeRange);

        List<Map<String, Object>> trend = bloodSugarRecordMapper.selectTrend(userId, startDate, endDate);
        if (trend == null || trend.isEmpty()) {
            trend = new ArrayList<>();
        }

        return trend;
    }

    @Override
    public List<Map<String, Object>> getByMeasureType(Long userId, String timeRange) {
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = getStartDateByTimeRange(endDate, timeRange);

        List<Map<String, Object>> result = bloodSugarRecordMapper.selectByMeasureType(userId, startDate, endDate);
        if (result == null || result.isEmpty()) {
            result = new ArrayList<>();
        }

        // 为每种测量类型添加名称
        for (Map<String, Object> item : result) {
            Integer measureType = (Integer) item.get("measureType");
            if (measureType != null) {
                switch (measureType) {
                    case 1:
                        item.put("measureTypeName", "空腹");
                        break;
                    case 2:
                        item.put("measureTypeName", "餐前");
                        break;
                    case 3:
                        item.put("measureTypeName", "餐后1小时");
                        break;
                    case 4:
                        item.put("measureTypeName", "餐后2小时");
                        break;
                    case 5:
                        item.put("measureTypeName", "睡前");
                        break;
                    case 6:
                        item.put("measureTypeName", "凌晨");
                        break;
                    case 7:
                        item.put("measureTypeName", "随机");
                        break;
                    default:
                        item.put("measureTypeName", "未知");
                }
            }
        }

        return result;
    }

    @Override
    public List<BloodSugarRecord> pageForAdmin(Long userId, LocalDate startDate, LocalDate endDate,
            int page, int size) {
        int offset = (page - 1) * size;
        return bloodSugarRecordMapper.selectPageForAdmin(userId, startDate, endDate, offset, size);
    }

    @Override
    public int countForAdmin(Long userId, LocalDate startDate, LocalDate endDate) {
        return bloodSugarRecordMapper.countForAdmin(userId, startDate, endDate);
    }

    @Override
    public int determineStatus(Double value, Integer measureType) {
        if (value == null || measureType == null) {
            return 1; // 默认正常
        }

        // 根据测量类型确定正常范围
        double lowerLimit, upperLimit;

        switch (measureType) {
            case 1: // 空腹
                lowerLimit = 3.9;
                upperLimit = 6.1;
                break;
            case 2: // 餐前
                lowerLimit = 3.9;
                upperLimit = 6.1;
                break;
            case 3: // 餐后1小时
                lowerLimit = 3.9;
                upperLimit = 10.0;
                break;
            case 4: // 餐后2小时
                lowerLimit = 3.9;
                upperLimit = 7.8;
                break;
            case 5: // 睡前
                lowerLimit = 3.9;
                upperLimit = 7.0;
                break;
            case 6: // 凌晨
                lowerLimit = 3.9;
                upperLimit = 6.1;
                break;
            case 7: // 随机
            default:
                lowerLimit = 3.9;
                upperLimit = 7.8;
                break;
        }

        // 判断血糖值状态
        if (value < lowerLimit) {
            return 2; // 偏低
        } else if (value > upperLimit) {
            return 3; // 偏高
        } else {
            return 1; // 正常
        }
    }

    /**
     * 根据时间范围获取开始日期
     */
    private LocalDate getStartDateByTimeRange(LocalDate endDate, String timeRange) {
        switch (timeRange) {
            case "day":
                return endDate;
            case "week":
                return endDate.minusDays(6); // 最近7天
            case "month":
                return endDate.minusDays(29); // 最近30天
            case "year":
                return endDate.minusDays(364); // 最近365天
            default:
                return endDate.minusDays(6); // 默认最近7天
        }
    }
}